﻿﻿using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Validation;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Serializers
{
    public class DeviceMessageInfoReadingSerializer : AbstractMessageSerializer<IDeviceMessageInfoReading>, IDeviceMessageInfoReadingSerializer
    {
        public DeviceMessageInfoReadingSerializer() : base(new DeviceMessageInfoReading())
        {
        }

        public override void Serializer(ArrayBufferWriter<byte> writer, IDeviceMessageInfoReading model)
        {
            ArgumentNullException.ThrowIfNull(model);
            if (model.Offset == null) 
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InvalidStateValue,
                    "读数时间偏移不能为null",
                    nameof(model.Offset),
                    "非空的字节数组",
                    null);
            if (model.Offset.Length != 2) throw new ArgumentOutOfRangeException(nameof(model), "Offset must be exactly 2 bytes long");
            SerializeWithHeader(
                writer,
                headerLength: 2,
                writeHeaderAction: w => w.Write(model?.Offset),
                serializeContentAction: w =>
                {
                    new DeviceMessageInfoReadingStatesSerializer().Serializer(writer, model.State ?? new DeviceMessageInfoReadingStates());
                });
        }
    }
}
